package com.azt.front.action.freemarker;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;


/**
 * @ClassName ContentCutDirective
 * @Description 文字过长的截断模板方法
 * @author Snowler
 * @Date 2016年8月8日 下午4:57:08
 * @version 1.0.0
 */
@Component("content_cut")
public class ContentCutDirective implements TemplateDirectiveModel {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void execute(Environment env, Map params, TemplateModel[] arg2, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		
		
		String content = DirectiveUtils.getString("content", params);//要截取的内容
		Integer length = DirectiveUtils.getInt("len", params);//截取长度
		String ending = DirectiveUtils.getString("ending", params , "...");//截取后结尾部分可自定义，默认是省略号
		
		if(content != null && length != null && length < content.length()){
			content = content.substring(0, length > content.length() ? content.length() : length) + ending;
		}
		
		Writer out = env.getOut();
		out.append(content);
	}

}
